/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import { MockConfigModuleInfo } from '@ohos/hvigor-arkts-compose';
import fse from 'fs-extra';
import path from 'path';

import { Dependency } from '../project/dependency/core/dependency-interface.js';
import { ModuleTaskService } from '../tasks/service/module-task-service.js';

import { getJson5Obj } from './json-util.js';

/**
 * 在mock-config场景，针对配置中的har和hsp，需要把key对应的真实路径传给mock，
 * 当前阶段，只查找到文件/文件夹路径，value可能不存在后缀，
 * 由于涉及到SUPPORT_EXTENSION，这块逻辑在ark-base阶段补充
 * @param configFilePath
 * @param service
 */
export const getMockConfigKey2ModuleInfoMap = (configFilePath: string, service: ModuleTaskService) => {
  const result: Record<string, MockConfigModuleInfo> = {};
  const mockConfig: any = getJson5Obj(configFilePath);
  if (!mockConfig || !Object.keys(mockConfig).length) {
    return result;
  }
  const map = new Map<string, Dependency>();
  service.getAllDependencies().forEach((dependency) => {
    map.set(dependency.getDependencyName(), dependency);
  });
  Object.keys(mockConfig).forEach((key) => {
    const parts = key.split(/[/\\]/);
    let id = parts.shift()!;
    const isRelative = id[0] === '.';
    if (isRelative) {
      return;
    }
    if (id[0] === '@' && parts.length > 0) {
      id += `/${parts.shift()}`;
    }
    if (!map.has(id)) {
      return;
    }
    const dependency = map.get(id)!;
    const pkgRoot = dependency.getDependencyRootPath();
    result[key] = {
      meta: {
        pkgPath: pkgRoot,
        pkgName: dependency.getPackageName(),
      },
      filePath: parts.length ? path.resolve(pkgRoot, ...parts) : dependency.getDependencyMainFilePath(),
    };
  });
  return result;
};

/**
 * 获取mock-config中source的绝对路径
 * @param configFilePath
 * @param modulePath
 */
export const getMockConfigSources = (configFilePath: string, modulePath: string) => {
  const sources: string[] = [];
  const mockConfig = getJson5Obj(configFilePath);
  if (!mockConfig) {
    return sources;
  }
  Object.values(mockConfig).forEach((value: any) => {
    const source = value.source;
    if (source) {
      const mockSourceFile = path.resolve(modulePath, source);
      if (fse.existsSync(mockSourceFile)) {
        sources.push(mockSourceFile);
      }
    }
  });
  return sources;
};
